package com.can.Service.Impl;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.DeleteResponse;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.can.Mapper.GameStoreMapper;
import com.can.Service.EsService;
import com.can.domain.po.Game;
import com.can.domain.vo.GameStoreVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
import co.elastic.clients.elasticsearch._types.Result;


@Service
@RequiredArgsConstructor
public class EsServiceImpl implements EsService {
//这里不需要写自动装配，因为RequiredArgsConstructor已经是自动写构造器注入了
    private final ElasticsearchClient client;
    @Autowired
    GameStoreMapper gameMapper;
    @Override
    public GameStoreVo addGameDoc(Game game) {
        try {
            // 创建索引请求
            IndexRequest<Game> request = IndexRequest.of(b -> b
                .index("games")          // 索引名称
//                .id("3")                 // 文档ID (可选，不指定则自动随机生成)
                .document(game)    );      // 要索引的文档
            IndexResponse response = client.index(request);
            System.out.println(response);
            return new GameStoreVo<>(200,"更新成功",null);
        } catch (IOException e) {
             return new GameStoreVo<>(500,"更新成功",null);
                             }

        }


            @Override
    public GameStoreVo deleteGameDocById(int id) {
        try {
            SearchResponse<Game> response = client.search(s -> s
                .index("games")
                .query(q -> q
                        .term(t -> t
                                .field("id")
                                .value(v -> v.longValue(id))
                        )
                ),
             Game.class
                                );

            Result res = client.delete(d -> d.index("games").id(response.hits().hits().get(0).id())).result(); // 执行删除操作

            if (res == Result.Deleted) {
                System.out.println("文档删除成功！");
            } else if (res == Result.NotFound) {
                System.out.println("文档不存在，无需删除。");
            } else {
                System.out.println("删除失败，状态是：" + res);
                return new GameStoreVo<>(500,"删除失败",null);
            }
            return new GameStoreVo<>(200,"删除成功",null);
        } catch (IOException e) {
             return new GameStoreVo<>(500,"删除失败",null);
                             }

        }

    @Override
    public GameStoreVo SearchGame(String name) {
          try {
                SearchResponse<Game> response = client.search(s -> s
                    .index("games")  // 索引名
                    .query(q -> q
                        .multiMatch(m -> m
                            .query(name)  // 搜索关键词
                            .fields("gamename", "content")  // 查询的字段
                        )
                    ), Game.class
            );

                List<Integer> ids = response.hits().hits().stream().map(i -> i.source().getId()).toList();
                if (ids.isEmpty()) {
                    return new GameStoreVo<>(404,"没有找到内容",null);
                }
                System.out.println("结果id:"+ids);
                List<Game> res = gameMapper.selectBatchIds(ids); // 返回符合ID的所有记录
              System.out.println();
                return new GameStoreVo<>(200,"",res);
            }catch (Exception e){
                    e.printStackTrace();
                    return new GameStoreVo<>(503,"",null);}
    }

    @Override
    public boolean queryGameDocById(int id) {
        try {
            SearchResponse<Game> response = client.search(s -> s
                            .index("games")
                            .query(q -> q
                                    .term(t -> t
                                            .field("id")
                                            .value(v -> v.longValue(id))
                                    )
                            ),
                    Game.class
            );
            int res=response.hits().hits().size();
            if (res > 0) {
                System.out.println("更新ES成功");
                return true;}
            else{
                System.out.println("更新ES失败");
                return false;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }}